package com.product;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.util.ShopAddOrDelUtil;
import com.util.ShopCartUtil;
import com.util.ShopRemoveUtil;
import com.vo.Product;
import com.vo.ShopCart;

public class ShopServlet extends HttpServlet {

	private List<ShopCart> list;
	

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();

		Product product = (Product) session.getAttribute("productinfo");
		int num = 0,sh_id=0,rsh_id=0;
		String type = null;
		if (request.getParameter("num") != null) {
			try {
				num = Integer.parseInt(request.getParameter("num"));
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		if(request.getParameter("type") != null){
			
				type = request.getParameter("type");
				
			
		}
		//
		if(request.getParameter("sh_id") != null){
			try {
				sh_id = Integer.parseInt(request.getParameter("sh_id"));
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		//用于删除购物车中的商品的id
		if(request.getParameter("rsh_id") != null){
			try {
				rsh_id = Integer.parseInt(request.getParameter("rsh_id"));
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		// 创建购物车
		if (list == null) {
			list = new ArrayList<ShopCart>();
			
		}
		ShopCart cart = new ShopCart();
		cart.setSp_id(product.getEp_id());
		
		cart.setSp_file_name(product.getEp_file_name());
		cart.setSp_name(product.getEp_name());
		cart.setSp_price(product.getNow_price());

		
			cart.setSp_num(1);
	
		if(type == null){
			ShopCartUtil.addProduct(list, cart);
		}else{
			ShopAddOrDelUtil.shopAdd(list, cart, type,sh_id);
		}
		if(rsh_id != 0){
			ShopRemoveUtil.removeShop(list, rsh_id);
		}
		session.setAttribute("shopcartlist", list);
		session.setAttribute("cartProduct", cart);
		
		/**request.getRequestDispatcher("shopping.jsp").forward(request, response);
		 *此处不用转发 不然在页面刷新时会出现bug
		 */
		response.sendRedirect("shopping.jsp");
	};

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

}
